'use strict';

let fs=require('fs');
let path=require('path')
let router=require('koa-router')();


function searchControllers(defaultDir){
    
    let files = fs.readdirSync(defaultDir);
    
    let resultFiles = files.filter((fileName) => {
        return fileName.endsWith('.js') && fileName !== 'index.js';
    });

    return resultFiles;
}

function registeForEachFile(files,currentPath){
  
    files.forEach(item => {
        let tmpPath = path.join(currentPath, item);
    
        let routerObj = require(tmpPath);
        
        for (let r in routerObj) {
            
            let type = routerObj[r][0];
           
            let fn = routerObj[r][1];
            if (type === 'get') {
                router.get(r, fn);
            } else {
                router.post(r, fn);
            }
        }
    })
}

module.exports = function(dir){
    let defaultDir=dir || '/controllers';
    
    let root = path.resolve('.');
    
    let resultControllerPath = path.join(root, defaultDir);

    let files=searchControllers(resultControllerPath);
    
    registeForEachFile(files,resultControllerPath);

    return router.routes();
};